<?php
/**
 * File: Model.php:YCMS
 * User: xiaoyan f@yanyunfeng.com
 * Date: 15-5-13
 * Time: 下午6:03
 * @Description
 */
class Models extends BaseController{

    public function init()
    {
        $this->addRoute('/model.list','_list');
        $this->addRoute('/model.add','addModel');
        $this->addRoute('/model.edit','editModel');
        $this->addRoute('/model.delete','deleteModel');
        $this->addRoute('/model.fields','fields');
        $this->addRoute('/model.field.add','addField');
        $this->addRoute('/model.field.edit','editField');
        $this->addRoute('/model.field.delete','deleteField');
        $this->addRoute('/model.field.check','checkField');
        $this->addRoute('/model.field.enable','enableField');
        $this->addRoute('/model.field.disable','disableField');
    }
    public function _list(){
        $list = DB()->table('common_models')->select();
        $this->render('models.list',array('list'=>$list));
    }
    public function addModel(){
        $this->render('models.add');
    }
    public function editModel(){
        $this->render('models.list');
    }
    public function deleteModel(){
        $this->render('models.list');
    }
    public function fields(){
        $modelId = $this->getInput()->get('id');
        $list = DB()
            ->table('common_fields f')
            ->where(array('model_id'=>$modelId))
            ->select();
        $this->render('models.fields',array('list'=>$list,'modelId'=>$modelId));
    }
    public function addField(){
        $modelId = $this->getInput()->get('id');
        if(isAjax() && !empty($_POST)){
           $this->saveField();//保存字段内容
        }
        $allType = FieldType::getAllType();
        $this->render('models.addField',array(
            'typeList'=>$allType,
            'modelId'=>$modelId,
            'mode' => 'insert'
        ));
    }
    public function editField(){
        $field_id = $this->getInput()->get('id');
        if(!$field_id) $this->message('数据传输错误,丢失字段编号');
        $where = array('field_id'=>$field_id);
        $fieldData = DB()->table('common_fields')->where($where)->get();
        if(!$fieldData) $this->message('没有找到要修改的字段数据');
        if(isAjax() && !empty($_POST)){
            $this->saveField();//保存字段内容
        }
        $fieldData['rules'] = unserialize($fieldData['rules']);
        if(in_array($fieldData['type'],array('radio','select'))){
            $fieldData['rules']['choice'] = $this->choiceToString($fieldData['rules']['choice']);
        }
        $allType = FieldType::getAllType();
        $this->render('models.addField',array(
            'modelId' => $fieldData['model_id'],
            'fieldData' => $fieldData,
            'typeList'=>$allType,
            'mode' => 'update'
        ));
    }
    public function deleteField(){
        $id = $this->getInput()->post('id');
        if(!$id || count($id) == 0) ajaxResponse(1,'请选择要操作的数据');
        try{
            DB()->delete('common_fields',array('field_id'=>$id));
            ajaxResponse();
        }catch (DBException $e){
            ajaxResponse(2,'删除字段失败');
        }
    }

    public function enableField(){
        $id = $this->getInput()->post('id');
        if(!$id || count($id) == 0) ajaxResponse(1,'请选择要操作的数据');
        try{
            DB()->update('common_fields',array('status'=>DataState::$enable),array('field_id'=>$id));
            ajaxResponse();
        }catch (DBException $e){
            ajaxResponse(2,'启用字段失败');
        }
    }
    public function disableField(){
        $id = $this->getInput()->post('id');
        if(!$id || count($id) == 0) ajaxResponse(1,'请选择要操作的数据');
        try{
            DB()->update('common_fields',array('status'=>DataState::$disable),array('field_id'=>$id));
            ajaxResponse();
        }catch (DBException $e){
            ajaxResponse(2,'启用字段失败');
        }
    }

    /**
     * 保存字段内容
     */
    private function saveField(){
        $saveData = $this->checkDataNull(array(
            array('model_id',201,'数据错误'),
            array('model_id',201,'数据错误'),
            array('identifier',202,'请填写字段标识'),
            array('title',203,'请填写字段名称'),
            array('type',204,'请选择字段类型'),
        ));
        if(in_array($saveData['type'],array('radio','select'))){
            $rules = $this->getInput()->post('rules');
            if(!$rules || !$rules['choice']){
                ajaxResponse(205,'请填写可选项内容');
            }
            $rules['choice'] = $this->parseChoice($rules['choice']);
            $saveData['rules'] = $rules;
        }
        $this->getPostData($saveData,'unit,allow_null,description');
        $backUrl = 'model.fields?id='.$saveData['model_id'];
        $act = $this->getInput()->get('act');
        if($act && in_array($act,array('insert','update'))){
            $data = array('url'=>$backUrl);
            if($act == 'insert'){
                $data['fid'] = $this->ajaxBasicInsert('common_fields',$saveData);
            }else if($act == 'update'){
                $field_id = $this->getInput()->post('field_id');
                if(!$field_id) ajaxResponse(205,'没有找到要修改的数据');
                $where = array('field_id'=>$field_id);
                $fieldData = DB()->table('common_fields')->where($where)->get();
                if(!$data) ajaxResponse(205,'没有找到要修改的数据');
                $this->ajaxBasicUpdate('common_fields',$saveData,$where);
            }
            ajaxResponse(0,'success',$data);
        }
        ajaxResponse(-1,'错误的请求');
    }
    private function parseChoice($str){
        $c = explode("\n",$str);
        $ss = array();
        foreach($c as $i => $so){
            preg_match('/^([A-Za-z0-9_]+?)=(.*)$/',$so,$si);
            $ss[] = array('text'=>$si[2],'value'=>$si[1]);
        }return $ss;
    }

    private function choiceToString($choice){
        $str = array();
        foreach($choice as $c){
            $str[] = $c['value'].'='.$c['text'];
        }
        return implode("\n",$str);
    }

    public function checkField(){
        $modelId = $this->getInput()->get('id');
        $fid = $this->getInput()->get('fid');
        $identifier = $this->getInput()->get('identifier');
        if($modelId && $identifier){
            if(!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/',$identifier)){
                ajaxResponse(2,'字段标识命名不正确');
            }
            $data = DB()->table('common_fields')
                ->where(array('model_id'=>$modelId))
                ->where(array('identifier'=>$identifier))
                ->get();
            if($data){
                if($fid && $fid == $data['field_id']) ajaxResponse();
                ajaxResponse(2,'该字段标识已经存在');
            }
            ajaxResponse();
        }
        ajaxResponse(3,'验证数据出错了');
    }
}